package org.example.server;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.DefaultChannelGroup;
import org.example.CreateGroupRequestPacket;
import org.example.CreateGroupResponsePacket;
import org.example.im.SessionUtil;

import java.util.ArrayList;
import java.util.List;

public class CreateGroupRequestHandler extends SimpleChannelInboundHandler<CreateGroupRequestPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, CreateGroupRequestPacket createGroupRequestPacket) {
        System.out.println("服务端准备创建群组..." + createGroupRequestPacket);
        // 1、创建群聊，获取所有加入群组的用户id
        List<String> userIds = createGroupRequestPacket.getUserIds();

        // 2、创建一个 channel 组， DefaultChannelGroup 需要构造参数 事件执行器
        DefaultChannelGroup channelGroup = new DefaultChannelGroup(ctx.executor());

        // 构造群组响应指令
        CreateGroupResponsePacket createGroupResponsePacket = new CreateGroupResponsePacket();
        String groupId = SessionUtil.randomUserId();
        createGroupResponsePacket.setGroupId(groupId);
        createGroupResponsePacket.setSuccess(true);
        List<String> userNames = new ArrayList<>();
        for (String userId : userIds) {
            Channel channel = SessionUtil.getChannel(userId);
            if (channel != null) {
                userNames.add(userId);
                // 3、将用户所在的连接添加到 channel 组中
                channelGroup.add(channel);
            }
        }
        createGroupResponsePacket.setUserNames(userNames);

        // 4、给每个客户都发送创建群消息通知
        channelGroup.writeAndFlush(createGroupResponsePacket);

        // 保存群聊信息
        SessionUtil.saveGroup(groupId, channelGroup);

        System.out.println("群创建成功，id 为[" + createGroupResponsePacket.getGroupId() + "]");
        System.out.println("群里面有:" + createGroupResponsePacket.getUserNames());
    }
}
